package com.iuie.ns.system.service.role.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.iuie.ns.frame.exception.ServiceException;
import com.iuie.ns.frame.persistence.dao.IGenericDao;
import com.iuie.ns.frame.service.impl.BaseServiceImpl;
import com.iuie.ns.frame.utils.StringUtils;
import com.iuie.ns.frame.web.dataset.vo.Page;
import com.iuie.ns.system.dao.authority.ISysAuthorityDao;
import com.iuie.ns.system.dao.role.ISysRoleDao;
import com.iuie.ns.system.mapper.role.SysRoleMapper;
import com.iuie.ns.system.service.role.ISysRoleService;
import com.iuie.ns.system.vo.authority.SysAuthorityVO;
import com.iuie.ns.system.vo.resource.SysResourceVO;
import com.iuie.ns.system.vo.role.SysRoleVO;

/**
 * 角色业务实现类
 * @author lj
 * @createTime 2017年1月1日 下午4:27:37
 */
@Service("roleService")
public class SysRoleServiceImpl extends BaseServiceImpl<SysRoleVO> implements ISysRoleService{

	@Autowired
	private ISysAuthorityDao authorityDao;
	
	@Autowired
	private ISysRoleDao roleDao;
	
	@Resource
	private SysRoleMapper roleMapper;
	
	@Override
	public SysRoleVO addOne(SysRoleVO role){
		// 1. 持久化role，使role获取roleId
		roleDao.save(role);
		
		Set<SysAuthorityVO> authorites = role.getAuthoritys();
		for(SysAuthorityVO auth:authorites) {
			// 2. 逐个持久化auth，使auth持有role
			auth.getRoles().add(role);
			authorityDao.save(auth);
		}
		
		return role;
	}

	@Override
	protected IGenericDao<SysRoleVO, Serializable> getGenericDao() {
		return roleDao;
	}

	@Override
	public List<SysRoleVO> findAllByPage(SysRoleVO role, Page page) {
		PageHelper.startPage(page.getPage(), page.getRows(), true);
		List<SysRoleVO> list = roleMapper.findByCondition(role);
		page.loadData(list);
		return list;
	}

	@Override
	public List<SysResourceVO> findMenusById(String roleId) {
		return roleMapper.findMenusById(roleId);
	}

    @Override
    public void saveRelation(String roleId, String[] menuIds) {
        if (StringUtils.isNotBlank(roleId) && menuIds != null && menuIds.length > 0) {
            roleMapper.deleteRelation(roleId, "menu");
            roleMapper.saveRelation(roleId, menuIds);
        } else {
            throw new ServiceException("保存失败，角色ID为空或菜单ID数组为空，roleId=" + roleId + ", menuIds = " + menuIds);
        }
    }
    
    @Override
    public SysRoleVO findById(String roleId) {
    	return roleMapper.findById(roleId);
    }
	
    @Override
    public void updateRole(SysRoleVO role) {
    	roleMapper.updateRole(role);
    }
}
